﻿using System.Collections.Generic;
using System.Linq;
using Fadada.FASC.SDK.DotNetCore.Interfaces;
using Fadada.FASC.SDK.DotNetCore.Model;
using System.Threading.Tasks;
using Fadada.FASC.SDK.DotNetCore.Attributes;
using Newtonsoft.Json;

namespace Fadada.FASC.SDK.DotNetCore.Services
{
    public class GetBodyRespService<T1, T2> : IGetBodyRespService<T1, T2>
        where T1 : class
        where T2 : class
    {
        public async Task<ResponseBodyInfo<T1>> GetBodyRespAsync(T2 inputBody, BaseInputInfo inputInfo, string token)
        {
            var attributeInfo = GetUrlAttribute(inputBody);
            inputInfo.ReqEndPoint = attributeInfo.Url;
            inputInfo.ReqMethod = attributeInfo.Method;
            var reqStr = JsonConvert.SerializeObject(inputBody, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            var body = new Dictionary<string, string>() { { "bizContent", reqStr } };
            IGetFromBodyService service = new GetFromBodyService();
            string result = await service.GetFromHttpBodyAsync(inputInfo, body, token);
            return JsonConvert.DeserializeObject<ResponseBodyInfo<T1>>(result);
        }
        private RemoteServiceAttribute GetUrlAttribute(T2 req)
        {
            var urlAttribute = req.GetType().GetCustomAttributes(false).First(r => r is RemoteServiceAttribute) as RemoteServiceAttribute;
            return urlAttribute;
        }
    }
}